//Module definition
var PAPI = PAPI || (function () {
    return {};
}());

PAPI.panel = (function(PAPI,$){
    //var numberOfSelectedRooms=0;
    var destinationMap = new Array();
    var airportMap = new Array();
    var airporAutompleteActive = false;
    //var openedErrorPopUps=false;
    var urlPath = autoCompleteUrl;
    var urlPathPapi;
    var mapTopDestinations = {"Turkey":"Turkey, Any","Greece":"Greece, Any","Tunisia":"Tunisia, Any","Majorca":"Majorca, Balearic Islands","Menorca":"Menorca, Balearic Islands","Tenerife":"Tenerife, Canary Islands",
    		"Lanzarote":"Lanzarote, Canary Islands","Cyprus":"Cyprus, Any","Cuba":"Cuba, Any","Mexico":"Mexico, Any","Portugal":"Portugal, Any","Gran Canaria":"Gran Canaria, Canary Islands","Egypt":"Egypt, Any","Florida":"Florida, USA",
    		"Morocco":"Morocco, Any","New York":"All New York City, USA","Paris":"Paris Centre, Paris, France","Rome":"Rome, Italy","Barcelona":"Barcelona City Centre (Eixample), Spain","Dubai":"Dubai, United Arab Emirates"}
    // flush parameters
    var newSearchFlag = false;

    var newSearch=function(roomNumber){
        var childValidated = true;
        for(var i=0;i<=roomNumber;i++){
            childValidated = validateChildren(i);
            if(!childValidated){
                break;
            }
        }
        newSearchFlag = childValidated;
    }

    var createMapValue=function(keyName, keyValue){
        if(keyValue != null && keyValue != undefined && keyValue != ''){
            $('<input/>').attr({ type: 'hidden', id: 'papiContext['+keyName+']', name: 'papiContext['+keyName+']', value: keyValue }).appendTo('#searchPanelFormId');
        }
    }

    var createMapValueList=function(keyName, keyListValue){

        if(keyListValue != null && keyListValue != undefined && keyListValue != ''){
            for(var i=0;i<keyListValue.length;i++){
                $('<input/>').attr({ type: 'hidden', id: 'papiContext['+keyName+']['+i+']', name: 'papiContext['+keyName+']', value: keyListValue[i] }).appendTo('#searchPanelFormId');
            }
        }
    }

    var updatePapiUrl=function(){
        $('#papiUrl').val(routingUrl);
    }

    var addNewRooms = function(totalRooms){
        var addNew=true;
        $('#numberOfRooms').val($('#paxCombination fieldset:visible').length+1);
        var numberPax=0;
        var numberOfFieldSetVisible=$('#paxCombination fieldset:visible').length-1;
        for(var i=0;i<=totalRooms;i++){
            if($('#searchAssistChild'+i).is(":visible")||$('#numAdultsError'+i).is(":visible")||$('#numInfantsError'+i).is(":visible")){
                addNew=false;
                break;
            }
        }
        for(var i=0;i<=numberOfFieldSetVisible;i++){
            numberPax=numberPax+parseInt($('#numAdults'+i).val())+parseInt($('#numChildren'+i).val());
        }
        if(addNew){
            if((numberPax+1)<=9){
                //This is because the default number of pax is 2, with this be avoid allowing adding a new room in case that more than 9 pax
//                $("#lastRoomIndexForValidate").val(parseInt($("#lastRoomIndexForValidate").val())+1);
                $(".facetsTop").removeClass('facetsStopTransition');

                for(var i=0;i<=totalRooms;i++){
                    $('#searchAssistChild'+i).removeClass('in');
                }
                $('fieldset[id^="room"]').each(function(index, element){
                    if(!$(element).is(':visible')){
                        $(element).fadeIn('slow');

                        $('.facetsTop').addClass("multiRoom_"+index+"");

                        lastRoomIndex = index;
                        return false;
                    }
                });
                $("#numAdults"+lastRoomIndex)[0].selectedIndex=0;
                if (lastRoomIndex > 0){
                    //numberOfSelectedRooms+=1;
                    $('#lastRoomIndex').val(lastRoomIndex);
                    $("#removeroom").fadeIn('slow');
                }

                if (lastRoomIndex == 2){
                    $("#addroom").addClass("hideAll");
                    $("#addroom").hide();
                }else{
                    $("#addroom").removeClass("hideAll");
                    $("#addroom").show();
                }

            }else{
                validateMoreThan9Pax(null);
            }
        }

        $('#topDestinations').removeClass('open');

    }

    var removeRooms =  function(totalRooms){
        var addNew=true;
        for(var i=0;i<=totalRooms;i++){
            if($('#searchAssistChild'+i).is(":visible")||$('#numAdultsError'+i).is(":visible")||$('#numInfantsError'+i).is(":visible")||'1'==$('#numberOfRooms').val()){
                addNew=false;
                break;
            }
        }
        $('#numberOfRooms').val(($('#paxCombination fieldset:visible').length)-1);
        if(addNew){

//            $("#lastRoomIndexForValidate").val(parseInt($("#lastRoomIndexForValidate").val())-1);
            $(".facetsTop").removeClass('facetsStopTransition');

            var lastRoomIndex=$('#paxCombination fieldset:visible').length-1;
            for(var i=0;i<=lastRoomIndex;i++){
                $('#searchAssistChild'+i).removeClass('in');
            }
            if (lastRoomIndex > 0){
                $('#room' + lastRoomIndex).fadeOut('slow');
                index = lastRoomIndex-1;
                $(".facetsTop").attr('class', 'facetPanel facetsTop multiRoom_'+index+'');

                lastRoomIndex--;
            }
            if (lastRoomIndex == 0){
                $("#removeroom").addClass("hideAll");
                $("#removeroom").hide();
            }
            $('#lastRoomIndex').val(lastRoomIndex);

            if (lastRoomIndex < 2){
                $("#addroom").removeClass("hideAll");
                $("#addroom").show();
            }

            if ($('#numberOfRooms').val() == 1){
                $("#removeroom").hide();
            }
        }

        $('#topDestinations').removeClass('open');

    }

    var topDestinations=function(){
        var $topDestinations = $('#topDestinations');
        if (!$topDestinations.hasClass("open")) {
            var facetHeight = $('.facetPanel').height() - 15;
            $topDestinations.css({'top': facetHeight});
        }
    }

    $(document).ready(function () {
        try{//This method puts the saved values of the last valid search and populates them WHEN the inputs have no values introduced by the customer
            var arrayCookieValues=getCookie("TCC_SearchParams");
            if(null!=arrayCookieValues && renderPanelFromCookieEnabled){
                arrayCookieValues=arrayCookieValues.split("@");
                if(renderPanelFromCookieEnabled){ //this vars are declared in the jsp tcHomeSearchPanel :)
                    renderRoomsAndPax(maxNumberOfRooms,arrayCookieValues[11],maxNumberOfPax,maxChildrenPerRoom,false);//this vars are declared in the jsp tcHomeSearchPanel :) they are retrieved originally from the db
                }
                if(''!=arrayCookieValues[0]){
                    $('#destinationDisplay').val(arrayCookieValues[0]);
                }
                if(''!=arrayCookieValues[1]){
                    $('#papiDestination').val(arrayCookieValues[1]);
                }
                if(''!=arrayCookieValues[2]){
                    $('#srchWhereFrom').val(arrayCookieValues[2]);
                }
                if(''!=arrayCookieValues[3]){
                    $('#srchWhereFromHidden').val(arrayCookieValues[3]);
                }
                if(''!=arrayCookieValues[4]){
                    var arrayDepartureDate=arrayCookieValues[4].split('-');
                }
                if(''!=arrayCookieValues[2]&&''!=arrayCookieValues[1]&&arrayDepartureDate[0]){
                    var date = new Date(arrayDepartureDate[2],getMonthNumber(arrayDepartureDate[1]),arrayDepartureDate[0]);
                }
                var currentDate = new Date();
                if(date>=currentDate){
                    if(''!=arrayCookieValues[4]){
                        $('#departureDate').val(arrayCookieValues[4]);
                    }
                }
                if(''!=arrayCookieValues[5]){
                    $('#departureDateHidden').val(arrayCookieValues[5]);
                }
                if('null'==arrayCookieValues[9]){
                    $('#papiFlexible1').prop('checked', false);
                }
                if(''!=arrayCookieValues[6]){
                    $('#srchDuration').val(arrayCookieValues[6]);
                }
                if(''!=arrayCookieValues[11]){
                    var lastRoomIndex=arrayCookieValues[11];
                }
                if(''==lastRoomIndex){
                    lastRoomIndex=0;
                }
                if(''!=arrayCookieValues[7]){
                    var arrayOfNumberOfAdults=arrayCookieValues[7].split(',');
                    for(var i=0;i<=arrayOfNumberOfAdults.length-1;i++){
                        if(''!=arrayOfNumberOfAdults[i]&&'null'!=arrayOfNumberOfAdults[i]){
                            document.getElementById('numAdults'+i).value=arrayOfNumberOfAdults[i];//this is with regular js cause it's doesn't work with jquery for some funny reason
                        }else{
                            console.log('controled error:null value in cookie in adults');
                        }
                    }
                }
                if(''!=arrayOfNumberOfAdults[8]){
                    var arrayOfNumberOfChildren=arrayCookieValues[8].split(',');
                    for(var i=0;i<=arrayOfNumberOfChildren.length-1;i++){
                        if(''!=arrayOfNumberOfChildren[i]&&'null'!=arrayOfNumberOfChildren[i]){
                            document.getElementById('numChildren'+i).value=arrayOfNumberOfChildren[i];//this is with regular js cause it's doesn't work with jquery for some funny reason
                        }else{
                            console.log('controled error:null value in cookie in children');
                        }
                    }
                }
                if(''!=arrayCookieValues[10]){
                    var arrayOfNumberOfChildrensAges=arrayCookieValues[10].split('*');
                }
                var counterChildAges=0;
                for(var i=0;i<=lastRoomIndex;i++){
                    for(var e=0;e<=maxChildrenPerRoom-1;e++){
                        if('null'!=arrayOfNumberOfChildrensAges[counterChildAges]){
                            document.getElementById('roomOccupancies'+i+'.childAges'+e).value=''!=arrayOfNumberOfChildrensAges[counterChildAges]?arrayOfNumberOfChildrensAges[counterChildAges]:'?';//this is with regular js cause it's doesn't work with jquery for some funny reason
                        }
                        counterChildAges+=1;
                    }
                }
            }else{
                renderRoomsAndPax(maxNumberOfRooms,2,maxNumberOfPax,maxChildrenPerRoom,true);//if there is no cookie we render the 2 extra rooms with display none
            }
        }catch(e){
            console.log(e);
        }

        checkChildrenNumber();

        var multiRoom0Height = 101;
        var multiRoom1Height = 160;
        var multiRoom2Height = 220;
        var lastRoomIndex = $('#paxCombination fieldset:visible').length-1;
        $(".facetsTop").attr('class', 'facetPanel facetsTop facetsStopTransition multiRoom_'+lastRoomIndex+'');
        var totalrooms=$('#paxCombination fieldset').length-1;
        $('#numberOfRooms').val($('#paxCombination fieldset:visible').length);
        showEditChildsOnStart(totalrooms);
    });


    var showEditChildsOnStart=function(totalrooms){
        for(var i=0;i<=totalrooms;i++){
            if($('#numChildren'+i).val()>0){
                $('#editChilds'+i).removeClass('fade');
            }
        }
    }

    var updateContext=function(context){
        $('input[name^="papiContext"]').remove();
        updatePapiUrl();
        for(var key in context){
            createMapValue(key, context[key]);
        }
        // destination
        createMapValue('resortCode', $("#papiDestination").val());
        // airport
        createMapValue('depAirport', $("#srchWhereFromHidden").val());
        // departureDate
        createMapValue('departureDate', $("#departureDateHidden").val());
        // duration
        createMapValue('duration', $('#srchDuration').find(":selected").val());
        // occupation
        addOccupation();
        $('input[name="stars"]').removeAttr('checked');
        $('#boardType option[value="0"]').attr("selected",true);
    }

    var addOccupation = function(){
        var i =0;
        var occupations = new Array();
        $('fieldset[id^="room"]').each(function(index, element){
            if($(element).is(':visible')){
                occupations[i]= getOccupation(index);
                i++;
            }
        });
        createMapValueList('occupation',occupations);
    }

    var getOccupation=function(index){
        var occupation = "";
            var adults = "#numAdults" + index;
            var children = "#numChildren"+ index;
			occupation = $(adults).val();

			var numChildren = $(children).val();//$('select[id^=chidren]').find(":selected").val();
			for (var i=0;i<numChildren;i++){
				occupation+="," + $('select[name="roomOccupancies['+index+'].childAges['+i+']"]').find(":selected").val();
			}
        return occupation
    }

    var updateStars=function(star){
        if($('#'+star+'_star').prop('checked') == true){
            $('#'+star+'_label').addClass('active');
        }else{
            $('#'+star+'_label').removeClass('active');
        }
    }

    var initStars=function(){
        for(var i=1;i<6;i++){
            updateStars(i);
        }
    }

    var filterUpdate=function(){
        // boardType
        $('input[name="papiContext[boardType]"]').remove();
        //createMapValue('boardType', getBoardType());
        // stars
        $('input[name^="papiContext[stars]"]').remove();
        //createMapValueList('stars', getStars());
        // submit the form
        SRP.search.searchAsyncCall();
    }

    var getBoardType=function(){
        return $("#boardType").find(":selected").val();
    }

    var getStars=function(){
        var values = new Array();
        for(var i=1;i<6;i++){
            if($('#'+i+'_star').prop('checked') == true && values.indexOf($('#'+i+'_star').val()) == -1){
                values.push($('#'+i+'_star').val());
            }
        }
        return values;
    }

	var displayDestinationError=function (){
		$("#destinationError").addClass('in');
		$("#destinationDisplay").addClass('facetInputError');
		hideAirportError();
	}

	var hideDestinationError = function (){
		$("#destinationError").removeClass('in');
		$("#destinationDisplay").removeClass('facetInputError');
	}
	var displayAirportError = function(){
		if($("#papiDestination").val() != ''){
			$("#airportError").addClass('in');
			$("#srchWhereFrom").addClass('facetInputError');
			hideDestinationError();
		}
	}

	var hideAirportError = function (){
		$("#airportError").removeClass('in');
		$("#airportError").removeClass('facetInputError');

	}

	function removePaxError(roomNumber){
        for(var i=0;i<=roomNumber;i++){
            $('#numAdultsError'+i).removeClass('in');
            $('#numInfantsError'+i).removeClass('in');
        }
    }

    function removeInfantsError(roomNumber){
        for(var i=0;i<=roomNumber;i++){
            $('#numInfantsError'+i).removeClass('in');
        }
    }

    var validateForm=function(){

		if(defaultDestination != undefined && defaultAirport != undefined){
			if(($('#destinationDisplay').val() == $('#destinationDisplay').attr('placeholder') || $('#destinationDisplay').val() == '') && $('#papiDestination').val()==''){
				$('#papiDestination').val(defaultDestination);
			}
			if(($('#srchWhereFrom').val() == $('#srchWhereFrom').attr('placeholder') || $('#srchWhereFrom').val() == '') && $('#srchWhereFromHidden').val()==''){
				$('#srchWhereFromHidden').val(defaultAirport);
			}
		}
        var destinationFound = validateInput('papiDestination');
        var destinationDisplayFound = validateInput('destinationDisplay');
        var airportDisplayFound = validateInput('srchWhereFrom');
        var airportFound = validateInput('srchWhereFromHidden');
        var dateFound = validateInput('departureDateHidden');
        var paxNumber = 0;

        var numberOfFieldSetVisible=$('#paxCombination fieldset:visible').length-1;
        for(var i=0;i<=numberOfFieldSetVisible;i++){
            paxNumber+=parseInt($("#numAdults"+i).val()) + parseInt($("#numChildren"+i).val())
        }

        $("#destinationError").removeClass('in');
        $("#airportError").removeClass('in');
        $("#dateError").removeClass('in');
		if(!destinationFound){
			$("#destinationError").addClass('in');
			$("#destinationDisplay").addClass('facetInputError');
			$("#destinationDisplay").focus();
		}else if(!airportFound){
			$("#airportError").addClass('in');
			$("#srchWhereFrom").addClass('facetInputError');
			//$("#srchWhereFrom").focus();
		}else if(!dateFound){
			$("#dateError").addClass('in');
			$("#departureDate").addClass('facetInputError');
			//$("#departureDate").focus();
		}else if(paxNumber > 9){
            $("#numAdultsError"+numberOfFieldSetVisible).addClass('in');
            $("#numAdultsError"+numberOfFieldSetVisible).addClass('facetInputError');
		}

		if(destinationFound && airportFound && dateFound && paxNumber < 10){
			return true;
		}else{
			return false;
		}
    }

    var cleanError=function(id){
        $("#"+id).removeClass('in');
    }

    var validateInput=function(id){
        // ie explorer get placeholder value as input value so we need to check that
        var placeHolderValue = $('#'+id).attr('placeholder');
        if($('#'+id).val() != null && $('#'+id).val() != ''){
            return true;
        }else{
            return false;
        }
    }

    var sendForm=function(roomNumber){
        var context;
        var resortCode;
        var depAirport;
        $("#lastRoomIndex").val($('#paxCombination fieldset:visible').length-1);
        $.each(destinationMap, function(index, element){
            if ($("#destinationDisplay").val() == element[0] && element[0]!=''){
                $("#papiUrl").val(element[2]);
                resortCode = element[1];
                context = element[3];
            }
        });
        $.each(airportMap, function(index, element){
            if ($("#srchWhereFrom").val() == element[0] && element[0]!=''){
                depAirport = element[1];
            }
        });
        if(depAirport != null && depAirport != ''){
            $("#srchWhereFromHidden").val(depAirport);
        }
        if(resortCode != null && resortCode != ''){
            $("#papiDestination").val(resortCode);
        }
        if(newSearchFlag){
            if(validateMoreThan9Pax("")&&validateForm()){
                if(isValidInfantsAndAdults()){
                    createPleaseWaitPopup ();
                    pleaseWaitPopup();
                    updateContext();
                    if(urlPathPapi != null && urlPathPapi != ''){
                        $("#papiUrl").val(urlPathPapi);
                    }
                    return true;
                }else{
                    validateInfantsAndAdults();
                }
            }
        }

        return false;
    }

    var createDatePicker=function() {
        var searchPanelAmend = document.getElementById('searchPanelAmend').value;
        $("#departureDate").datepicker({
            minDate: 1,
            maxDate: '+18M',
            dateFormat: "dd-M-yy",
            numberOfMonths: 1,
            firstDay: 1,
            changeMonth: true,
            changeYear: true,
            onSelect: function(dateText, objDatepicker){
                //configureLocale($('#siteId').val());
                updateHiddenDate();
            }
        });

        if ( $('input[id^="papiContextdepartureDate"]').size()==0
			&& $('#departureDate').val() == ''){
            $('#departureDate').datepicker('setDate', '+1d');
            updateHiddenDate();
        }
    }

    var updateHiddenDate=function(){
        var currentDate = $( "#departureDate" ).datepicker( "getDate" );
        var month = currentDate.getMonth()+1;
        if(month<10){
            month = '0'+month;
        }
        var formattedDate = currentDate.getFullYear()+''+month+''+currentDate.getDate();
        $("#departureDateHidden").val(formattedDate);
    }

// :formTipBottom - show
    $(function () {
        "use strict";
        $('body').on('change','[data-toggle=formTipBottom]', function (e) {
            var childValidation=true;
            if(e.currentTarget.id.indexOf("numChildren")!=-1){
                var numberOfFieldSetVisible=$('#paxCombination fieldset:visible').length-1;
                var childrenNumber=0;
                var adultsNumber=0;
                for(var i=0;i<=numberOfFieldSetVisible;i++){
                    adultsNumber+=parseInt($('#numAdults'+i).val());
                    childrenNumber+=parseInt($('#numChildren'+i).val());
                }
            }else{
                childValidation=false;
            }

            var formFieldOffset = $(this).offset(),
                parentFormRowOffset = $(this).closest('.cell').offset(),
                dataTarget = $(this).attr('data-target'),
                targetWidth = $(dataTarget).outerWidth(true),
                targetTop = formFieldOffset.top - parentFormRowOffset.top + $(this).outerHeight() + 5,
                targetLeft = formFieldOffset.left - parentFormRowOffset.left + $(this).outerWidth()/2 - (targetWidth/2);
            if (e.currentTarget.value >0&&(childrenNumber+adultsNumber <= 9)){
                $(dataTarget).addClass('in').css({'left': targetLeft, 'top': targetTop});
            }else{
                if(childValidation&&e.currentTarget.value >0){
                    $(dataTarget).removeClass('in');
                    $("#numAdultsError"+numberOfFieldSetVisible).addClass('in');
                    $("#numAdultsError"+numberOfFieldSetVisible).addClass('facetInputError');
                }
            }
        });
    });


    var positionChilds=function(roomNumber){
        var e=$('#numChildren'+roomNumber);
        var numberOfFieldSetVisible=$('#paxCombination fieldset:visible').length-1;
        var childrenNumber=0;
        var adultsNumber=0;
        for(var i=0;i<=numberOfFieldSetVisible;i++){
            adultsNumber+=parseInt($('#numAdults'+i).val());
            childrenNumber+=parseInt($('#numChildren'+i).val());
        }

        var formFieldOffset = $(e).offset(),
            parentFormRowOffset = $(e).closest('.cell').offset(),
            dataTarget = $(e).attr('data-target'),
            targetWidth = $(dataTarget).outerWidth(true),
            targetTop = formFieldOffset.top - parentFormRowOffset.top + $(e).outerHeight() + 5,
            targetLeft = formFieldOffset.left - parentFormRowOffset.left + $(e).outerWidth()/2 - (targetWidth/2);
        if (e.val()>0&&(childrenNumber+adultsNumber <= 9)){
            $(dataTarget).css({'left': targetLeft, 'top': targetTop});
            openChildPanelFromButton('#searchAssistChild'+roomNumber,roomNumber);
        }else{
            $(dataTarget).removeClass('in');
            $("#numAdultsError"+numberOfFieldSetVisible).addClass('in');
            $("#numAdultsError"+numberOfFieldSetVisible).addClass('facetInputError');
        }
    }

    var validateInfantsAndAdults=function() {
        var infantsNumber=prepareInfants();
        var numberOfFieldSetVisible = $('#paxCombination fieldset:visible').length - 1;
        for (var i = 0; i <= numberOfFieldSetVisible; i++) {
            if (parseInt($('#numAdults' + i).val()) < infantsNumber[i]) {
                $('#searchAssistChild'+i).removeClass('in');
                $("#numInfantsError"+i).addClass('in');
                $("#numInfantsError"+i).addClass('facetInputError');
                break;
            }
        }
    }

    var isValidInfantsAndAdults=function() {
        var infantsNumber=prepareInfants();
        var valid=true;
        var numberOfFieldSetVisible = $('#paxCombination fieldset:visible').length - 1;
        for (var i = 0; i <= numberOfFieldSetVisible; i++) {
            if (parseInt($('#numAdults' + i).val()) < infantsNumber[i]) {
                valid=false;
                break;
            }
        }
        return valid;
    }

    function prepareInfants() {
        var infantsNumber = new Array();
        var numberOfFieldSetVisible = $('#paxCombination fieldset:visible').length - 1;
        infantsNumber[0] = 0;
        infantsNumber[1] = 0;
        infantsNumber[2] = 0;
        for (var i = 0; i <= numberOfFieldSetVisible; i++) {
            var numChild=parseInt($('#numChildren'+i).val())-1;
            for (var e = 0; e <= numChild; e++) {
                if (document.getElementById('roomOccupancies' + i + '.childAges' + e).value == '1') {
                    infantsNumber[i] += 1;
                }
            }
        }
        return infantsNumber;
    }

    var removeChildsPanel=function(){
        var numberOfFieldSetVisible = $('#paxCombination fieldset:visible').length - 1;
        for(var i=0;i<=numberOfFieldSetVisible;i++){
            $('#searchAssistChild'+i).removeClass('in');
        }
    }

    var validateMoreThan9Pax=function(caller){
        var numberPax=0;
        var numberOfFieldSetVisible=$('#paxCombination fieldset:visible').length-1;
        //var popupsOpened=false;
        for(var i=0;i<=numberOfFieldSetVisible;i++){
            numberPax=numberPax+parseInt($('#numAdults'+i).val())+parseInt($('#numChildren'+i).val());
        }
//        for(var i=0;i<=numberOfFieldSetVisible;i++){
//            if($('#searchAssistChild'+i)){
//                popupsOpened=true;
//                break;
//            }
//        }

        //if(!popupsOpened){
            if(null==caller){
                numberPax+=1;//this piece of shit is because when i add a new room, and i already have 9 pax, i can't allow that action, so therefore i have to open the pop up of the morethan9pax validation
            }
            removePaxError(numberOfFieldSetVisible);
            if(numberPax > 9){
                for(var i=0;i<=numberOfFieldSetVisible;i++){
                    $('#searchAssistChild'+i).removeClass('in');
                }
                $("#numAdultsError"+numberOfFieldSetVisible).addClass('in');
                $("#numAdultsError"+numberOfFieldSetVisible).addClass('facetInputError');
                return false;
            }else{
                return true;
            }
        //}
    }

    var validateChildAgesPanel=function(roomNumber,step,caller){
        if(step=='button'||step=='exit'){
            if(validateMoreThan9Pax(caller)&&validateChildren(roomNumber)){
                if($("#numChildren" + roomNumber)==0){
                    $('#editChilds'+roomNumber).addClass('fade');
                }
                if(step=='exit'){
                    for(var i=0;i<=roomNumber;i++){
                        $('#searchAssistChild'+i).removeClass('in');
                    }
                }
            }

        }else if(step=='exitbutton'){
            $('#numChildren'+roomNumber).val(0);
            for(var i=0;i<=roomNumber;i++){
                $('#searchAssistChild'+i).removeClass('in');
            }
            $('#editChilds'+roomNumber).removeClass('in');
            $('#editChilds'+roomNumber).addClass('fade');
        }
        //checkChildrenNumber();
    }

//    var closeChildAgesPanel=function(roomNumber){
//        $("#searchAssistChild" + roomNumber).removeClass('in');
//    }

    var openChildPanelFromButton=function(childPanelId,roomNumber){
        var adultsNumber=0;
        var childrenNumber=0;
        var numberOfFieldSetVisible=$('#paxCombination fieldset:visible').length-1;
        for(var i=0;i<=numberOfFieldSetVisible;i++){
            adultsNumber+=parseInt($('#numAdults'+i).val());
            childrenNumber+=parseInt($('#numChildren'+i).val());
        }
        if(adultsNumber+childrenNumber<=9){
            if(isValidInfantsAndAdults()){
                for(var i=0;i<=numberOfFieldSetVisible;i++){
                    $('#searchAssistChild'+i).removeClass('in');
                }
                removeInfantsError(roomNumber);
                $(childPanelId).addClass('in');
                PACKAGE.panel.displayChilds(6, $('#numChildren'+roomNumber).val(), roomNumber);
            }else{
                ///////findme
                validateInfantsAndAdults();
            }
        }
    }

    var validateChildren=function(roomNumber){
        var isEmpty = true;
        $('select[id^="roomOccupancies"]').each(function(){
            var numChilds = $(this).attr('numChild');
            //only God and I know how this works, now only God knows... Now Sergio knows as well muahahahahahahahaha!!!!!!
            $("#childAgeR" +roomNumber + "C" + numChilds).each(function(){
                if ($("#childAgeR" +roomNumber + "C" + numChilds ).is(':visible')){
                    if($(this).find('select:first').val()==0){
                        isEmpty = false;
                        $('#childAgeErrorR'+roomNumber).show();
                        $(this).find('select:first').addClass('facetInputError');
                        //return false;
                    }
                }
            });
        });
        return isEmpty;
    }

//    var cleanChildrenError=function(numChild,roomNumber){
//        var atLeastOne=false;
//        for(var i=0;i<=roomNumber;i++){
//            for(var e=0;e<=5;e++){
//                if(document.getElementById('roomOccupancies'+i+'.childAges'+e).className=='facetInputError'){
//                    atLeastOne=true;
//                    break;
//                }
//            }
//        }
//        if(!atLeastOne){
//            $('#childAgeErrorR').hide()
//        }
//        $('[id*="childAges' + numChild + '"]').removeClass('facetInputError');
//    }

    var cleanChildrenError=function(numChild,roomNumber){
        $('#childAgeErrorR'+roomNumber).hide();
        $('[id*="childAges' + numChild + '"]').removeClass('facetInputError');
        //validateChildren(roomNumber);
    }

    var calculatePapiPagination=function(page,maxResponses){

        var resultsPerPage;
        if (maxResponses != null){
            resultsPerPage = maxResponses;
        }else {
            resultsPerPage = document.getElementById('SelectMaxResponses').options[document.getElementById('SelectMaxResponses').selectedIndex].value;
        }
        var start = page * resultsPerPage;
        var end = (parseInt(start*1 + resultsPerPage*1))-1;
        var maxResultsPerPage = 0;

        if ($('#papiContextstart') != null && $('#papiContextend') != null){
            $('#papiContextstart').val(parseInt(start));
            $('#papiContextend').val(parseInt(end));
        }
    }

    var hideFilters=function(){
        $('#facetFilterBy').fadeOut('slow');
    }


    var airportAutomcomplete=function(){
        if(!airporAutompleteActive){
			if($("#papiDestination").val() != ''){
            var userDestination = $("#destinationDisplay").val();
				var destinationFound = false;
                var params = {resort: userDestination};
                var jqxhr = $.ajax({url:urlPath, dataType:'json', data:params, headers:{'SESSIONID':getCookie("JSESSIONID"), 'DEVICEID':getCookie("DEVICEID")}}).done(function(data){
                    $('#papiDestination').val('');
                    $('#srchWhereFromHidden').val('');
                    destinationTags = new Array();
                    $.each(data._embedded.resorts, function(index, element) {
                        if(element.title==userDestination){
                            $('#papiDestination').val(element.code);
                            destinationMap[0]= new Array(2);
                            destinationMap[0][0]= element.title;
                            destinationMap[0][1]= data._embedded.resorts[index].code;
                            destinationMap[0][2]= data._embedded.resorts[index]._links.routedSearch.href;
                            destinationMap[0][3]=data._embedded.resorts[index]._links.routedSearch.context;
                            destinationTags[0] = element;
							destinationFound = true;
                        }
                    });
					if(destinationFound){
                    airportTags = new Array();
						$.each(destinationTags[0]._links.routedSearch.params.depAirport.params.list, function(index, element) {
                        airportMap[index]= new Array(2);
                        airportTags[index] = element.title;
                        airportMap[index][0] = element.title;
                        airportMap[index][1] = element.value;
                    });
                    $("#srchWhereFrom").autocomplete({source: airportTags, appendTo: ".facetsTop", minLength:0}).focus(function(){
                        $("#srchWhereFrom").autocomplete("search");
                    });
                    airporAutompleteActive = true;
					}else{
						displayDestinationError();
					}
                });
	}else{
				displayDestinationError();
            }
		}else if($("#papiDestination").val() == ''){
			displayDestinationError();
        }
    }
    jQuery.support.cors = true;
    var airportError = false;
	destinationTags = new Array();

    $(document).ready(function() {
        $("#destinationDisplay").blur(function() {
            hideDestinationError();
            airportTags = new Array();
            if($('#papiDestination').val() == ''){
                if(destinationTags != null && destinationTags.length>0){
                    var choosenIndex = 0;
                    $.each(destinationTags, function(index, element) {
                        if($("#destinationDisplay").val() == element.title){
                            choosenIndex = index;
                        }
                    });

                    if(choosenIndex == 0){
                        $("#destinationDisplay").val(destinationTags[choosenIndex].title);
                        $('#papiDestination').val(destinationTags[choosenIndex].code);
                    }
                    $.each(destinationTags[choosenIndex]._links.routedSearch.params.depAirport.params.list, function(index, element) {
                        airportMap[index]= new Array(2);
                        airportTags[index] = element.title;
                        airportMap[index][0] = element.title;
                        airportMap[index][1] = element.value;
                    });
                    $("#srchWhereFrom").autocomplete({
                        source: airportTags,
                        appendTo: ".facetsTop",
                        minLength:0,
                        response: function(event, ui){
                            if(ui.content.length === 0){
                                if($('#papiDestination').val() == ''){
                                    displayDestinationError();
                                }else{
                                    displayAirportError();
                                }
                            }else{
                                $("#airportError").removeClass('in');
                                $("#srchWhereFrom").removeClass('facetInputError');
                                airportError = false;
                            }
                        }, autoFocus: true
                    }).focus(function(){
                            $("#srchWhereFrom").autocomplete("search");
                        }).blur(function() {
                            $("#airportError").removeClass('in');
                            $("#srchWhereFrom").removeClass('facetInputError');
                        });
                    $("#destinationDisplay").removeClass('facetInputError');
                }else{
                    //$("#destinationDisplay").val('');
                }
            }
        }).change(function() {
                var placeHolderValue = $('#destinationDisplay').attr('placeholder');
                if($("#destinationDisplay").val().length < 2 || $('#destinationDisplay').val() == placeHolderValue){
                    $('#papiDestination').val('');
                    $("#srchWhereFrom").val('');
                    $('#srchWhereFromHidden').val('');
                    destinationTags = new Array();
                    airportTags = new Array();
                    $("#srchWhereFrom").autocomplete({source: airportTags, appendTo: ".facetsTop", minLength:0});
                }
            }).autocomplete({
                source: function(request, response) {
                    $.ajax({url:urlPath,  crossDomain : true, dataType:'json', data:{resort: request.term},
                    	headers: {'SESSIONID':getCookie("JSESSIONID"), 'DEVICEID':getCookie("DEVICEID")},
                        success: function(data) {
                            $('#srchWhereFrom').val('');
                            $('#papiDestination').val('');
                            $('#srchWhereFromHidden').val('');
                            destinationTags = new Array();
                            if(data._embedded.resorts == null || data._embedded.resorts.length == 0){
                                displayDestinationError();
                                $('#destinationDisplay').autocomplete('close');
                                destinationMap = new Array();
                                airportTags = new Array();
                                $("#srchWhereFrom").autocomplete({source: airportTags, appendTo: ".facetsTop", minLength:0});
                            }else{
                                hideDestinationError();
                                $.each(data._embedded.resorts, function(index, element) {
                                    destinationMap[index]= new Array(2);
                                    destinationMap[index][0]= element.title;
                                    destinationMap[index][1]= data._embedded.resorts[index].code;
                                    destinationMap[index][2]= data._embedded.resorts[index]._links.routedSearch.href;
                                    destinationMap[index][3]=data._embedded.resorts[index]._links.routedSearch.context;
                                    destinationTags[index] = element;
                                });
                                airportTags = new Array();
                                if (data._embedded.resorts != ''){
                                    urlPathPapi = data._embedded.resorts[0]._links.routedSearch.href;
                                }

                                response($.map(destinationTags, function(item) {
                                    return {
                                        label: item.title,
                                        value: item.title
                                    }
                                }));
                            }
                        }
                    });
                },  minLength: 3,
                autoFocus: true
            }).on( "autocompleteselect", function( event, ui ) {
                airporAutompleteActive = true;
                $("#srchWhereFrom").removeAttr("disabled");
                for(var i = 0;i<destinationTags.length;i++){
                    if(destinationTags[i].title == ui.item.value){
                        $("#papiUrl").val(destinationTags[i]._links.routedSearch.href);
                        $('#papiDestination').val(destinationTags[i].code);
                        airportTags = new Array();
                        $.each(destinationTags[i]._links.routedSearch.params.depAirport.params.list, function(index, element) {
                            airportMap[index]= new Array(2);
                            airportTags[index] = element.title;
                            airportMap[index][0] = element.title;
                            airportMap[index][1] = element.value;
                        });
                        $("#srchWhereFrom").autocomplete({
                            appendTo: ".facetsTop",
                            source: airportTags,
                            minLength:0,
                            response: function(event, ui) {
                                if (ui.content.length === 0) {
                                    displayAirportError();
                                } else {
                                    hideAirportError();
                                }
                            }, autoFocus: true
                        }).focus(function(){
                                $("#srchWhereFrom").autocomplete("search");
                            });
                        if(event.which != 9){
                            $("#srchWhereFrom").focus();
                        }
                        hideAirportError();
                        break;
                    }
                }
            });

        if(window.location.pathname.indexOf('searchresult') != -1){
            initStars();
        }
        $("#srchWhereFrom").focus(function(){
            hideAirportError();
        }).on( "autocompleteselect", function( event, ui ) {
                if(event.which != 9){
                    $("#departureDate").focus();
                    $("#srchWhereFrom").removeClass('facetInputError');
                }
            });
        $('#searchPanelFormId').keypress(function(event){
            // prevent collapsed action
            if (event.keyCode == 10 || event.keyCode == 13) {
                event.preventDefault();
                // trigger button click as doesn't work if we trigger form submit
                //$("#search-btn").click();
            }

        });
        createDatePicker();  //TODO check if this doesn't break other thing
    });
    var getCookie=function(c_name)
    {
        var c_value = document.cookie;
        var c_start = c_value.indexOf(" " + c_name + "=");
        if (c_start == -1)
        {
            c_start = c_value.indexOf(c_name + "=");
        }
        if (c_start == -1)
        {
            c_value = null;
        }
        else
        {
            c_start = c_value.indexOf("=", c_start) + 1;
            var c_end = c_value.indexOf(";", c_start);
            if (c_end == -1)
            {
                c_end = c_value.length;
            }
            c_value = unescape(c_value.substring(c_start,c_end));
        }
        return c_value;
    }
    var getMonthNumber=function(month){
        var monthNumber="";
        if(month=="Jan"){
            monthNumber=0;
        }else if(month=="Feb"){
            monthNumber=1;
        }else if(month=="Mar"){
            monthNumber=2;
        }else if(month=="Apr"){
            monthNumber=3;
        }else if(month=="May"){
            monthNumber=4;
        }else if(month=="Jun"){
            monthNumber=5;
        }else if(month=="Jul"){
            monthNumber=6;
        }else if(month=="Aug"){
            monthNumber=7;
        }else if(month=="Sep"){
            monthNumber=8;
        }else if(month=="Oct"){
            monthNumber=9;
        }else if(month=="Nov"){
            monthNumber=10;
        }else if(month=="Dec"){
            monthNumber=11;
        }
        return monthNumber;
    }
    //this function paints the additional rooms and paxmix on the tc panel using the info read fromt he cookie in js
    var renderRoomsAndPax = function(maxNumberOfRooms,selectedNumberOfRooms,maxNumberOfPax,maxChildrenPerRoom,displayNoneEnabled){
        var maxChildrenAge=17;
        var numberOfPaintedRooms='0';
        for(var i=1;i<=maxNumberOfRooms;i++){
            var fieldSet = document.createElement('fieldset');
            fieldSet.id='room'+i;
            if(displayNoneEnabled){
                fieldSet.setAttribute('style','display:none;');
            }else{
                if(i>selectedNumberOfRooms){
                    fieldSet.setAttribute('style','display:none;');
                    numberOfPaintedRooms++;
                }
            }
            var legend = document.createElement('legend');
            legend.className='cell';
            legend.innerHTML='Room'+(i+1);
            fieldSet.appendChild(legend);
            var divAdults1 = document.createElement('div');
            divAdults1.id='room'+i+'.adults';
            divAdults1.className='cell';
            var label1 = document.createElement('label');
            label1.innerHTML='Adults';
            divAdults1.appendChild(label1);
            fieldSet.appendChild(divAdults1);
            document.body.appendChild(fieldSet);
            var selectAdults = document.createElement('select');
            selectAdults.id='numAdults'+(i);
            selectAdults.name='roomOccupancies['+(i)+'].numberOfAdults';
            selectAdults.setAttribute("onchange", 'PAPI.panel.putZeroInChilds(\''+maxNumberOfRooms+'\',\''+i+'\');PAPI.panel.removePaxError();PAPI.panel.validateMoreThan9Pax(this);');
            for(var e=1;e<=maxNumberOfPax;e++){
                var option1 = document.createElement('option');
                option1.value=new String(e);
                option1.innerHTML=option1.value;
                if(e==1){
                    option1.setAttribute('selected', 'selected');
                }
                selectAdults.appendChild(option1);
            }
            divAdults1.appendChild(selectAdults);
            var divAdults2 = document.createElement('div');
            divAdults2.className='formTipBottom formTipError fade childAges';
            divAdults2.id='numAdultsError'+i;
            var divAdults3 = document.createElement('div');
            divAdults3.className='formTipBottom-hd';
            var iElement = document.createElement('i');
            iElement.className='mediumIcon-warning';
            divAdults3.appendChild(iElement);
            var h3 = document.createElement('h3');
            h3.innerHTML='Booking for more than 9 people?';
            divAdults3.appendChild(h3);
            var p = document.createElement('p');
            p.innerHTML='Please call <strong>0844 879 8493</strong> to speak to one of our advisors who will help you with your holiday needs.';
            divAdults3.appendChild(p);
            divAdults2.appendChild(divAdults3);
            divAdults1.appendChild(divAdults2);
            //end of divAdults
            var divChildren1 = document.createElement('div');
            divChildren1.id='room'+i+'.childrens';
            divChildren1.className='cell';
            var label2 = document.createElement('label');
            label2.innerHTML='Children (0-17)';
            divChildren1.appendChild(label2);
            var selectChildren1 = document.createElement('select');
            selectChildren1.id='numChildren'+i;
            selectChildren1.name='roomOccupancies['+i+'].numberOfChildren';
            selectChildren1.setAttribute('data-target','#searchAssistChild'+i);
            selectChildren1.setAttribute('style','z-index: 10;');
            selectChildren1.setAttribute('data-toggle','formTipBottom');
            selectChildren1.setAttribute('onchange', "PAPI.panel.removeChildsPanel();PAPI.panel.validateMoreThan9Pax(this);PACKAGE.panel.updateSearchPanelChildAge('"+maxChildrenPerRoom+"',this,'"+i+"');PAPI.panel.removePaxError('"+i+"');");
            for(var e=0;e<=maxChildrenPerRoom;e++){
                var option2 = document.createElement('option');
                option2.value=new String(e);
                option2.innerHTML=option2.value;
                if(e==0){
                    option2.setAttribute('selected', 'selected');
                }
                selectChildren1.appendChild(option2);
            }
            divChildren1.appendChild(selectChildren1);
            var divChildren2 = document.createElement('div');
            divChildren2.className='formTipBottom formTipError fade childAges';
            divChildren2.id='numInfantsError'+i;
            var divChildren3 = document.createElement('div');
            divChildren3.className='formTipBottom-hd';
            var iElement2 = document.createElement('i');
            iElement2.className='mediumIcon-warning';
            divChildren3.appendChild(iElement2);
            var h3_2 = document.createElement('h3');
            h3_2.innerHTML='More infants than adults?';
            divChildren3.appendChild(h3_2);
            var p2 = document.createElement('p');
            p2.innerHTML='Please call <strong>0844 879 8493</strong> to speak to one of our advisors who will help you with your holiday needs.';
            divChildren3.appendChild(p2);
            divChildren2.appendChild(divChildren3);
            divChildren1.appendChild(divChildren2);
            var a = document.createElement('a');
            a.href='#';
            a.title='edit';
            a.className='fade editChild';
            a.setAttribute('onclick','PAPI.panel.positionChilds('+i+');');
            a.id='editChilds'+i;
            var iElement3 = document.createElement('i');
            iElement3.className='icon-openEdit';
            a.appendChild(iElement3);
            divChildren1.appendChild(a);
            //End of divchildren, we start with the panel of the chidages which is inside divChildren1
            var divPanelAges1 = document.createElement('div');
            divPanelAges1.id='searchAssistChild'+i;
            divPanelAges1.className='formTipBottom fade childAges';
            var divPanelAges2 = document.createElement('div');
            divPanelAges2.className='formTipBottom-hd';
            var button = document.createElement('button');
            button.className='close';
            button.setAttribute('data-dismiss','close');
            //button.type='button';
            button.setAttribute('onclick', "PAPI.panel.validateChildAgesPanel('"+i+"','exitbutton',this)");
            button.innerHTML='x';
            var h3_3 = document.createElement('h3');
            h3_3.innerHTML='What are their ages on date of return?';
            divPanelAges2.appendChild(button);
            divPanelAges2.appendChild(h3_3);
            divPanelAges1.appendChild(divPanelAges2);
            var divPanelAges3 = document.createElement('div');
            divPanelAges3.className='formTipBottom-bd';
            var divPanelAges4 = document.createElement('div');
            divPanelAges4.className='formRow';
            for(var e=0;e<maxChildrenPerRoom;e++){
                var divChildAges = document.createElement('div');
                divChildAges.className='cell';
                divChildAges.id='childAgeR'+i+'C'+e;
                var label3 = document.createElement('label');
                label3.innerHTML='Child&nbsp;'+(e+1)+'&nbsp;age';
                divChildAges.appendChild(label3);
                var selectAgeChild = document.createElement('select');
                selectAgeChild.setAttribute('onchange',"PAPI.panel.cleanChildrenError('"+e+"','"+i+"');PAPI.panel.validateChildAgesPanel('"+i+"','button',this);");
                selectAgeChild.setAttribute('numchild',e);
                selectAgeChild.setAttribute('roomnumber',i);
                selectAgeChild.name='roomOccupancies['+i+'].childAges['+e+']';
                selectAgeChild.id='roomOccupancies'+i+'.childAges'+e;
                for(var u=0;u<=maxChildrenAge;u++){
                    var option3 = document.createElement('option');
                    option3.value=new String(u);
                    if (u == 0) {
                        option3.innerHTML = '?';
                        option3.setAttribute('selected', 'selected');
                    } else if (u == 1) {
                        option3.innerHTML = '&lt;2';
                    } else {
                        option3.innerHTML = option3.value;
                    }
                    selectAgeChild.appendChild(option3);
                }
                divChildAges.appendChild(selectAgeChild);
                divPanelAges4.appendChild(divChildAges);
                if(e==maxChildrenPerRoom-1){
                    var divPanelAges5 = document.createElement('div');
                    divPanelAges5.className='childAges';
                    divPanelAges5.id='childAgeErrorR'+i;
                    divPanelAges5.setAttribute('style','display: none;');
                    var p = document.createElement('p');
                    var strong = document.createElement('strong');
                    strong.innerHTML='<i class="mediumIcon-warning"></i> Please specify child\'s age.';
                    p.appendChild(strong);
                    divPanelAges5.appendChild(p);
                    divPanelAges4.appendChild(divPanelAges5);
                }
            }
            var divPanelAges6 = document.createElement('div');
            divPanelAges6.className='formTipBottom-ft';
            var a3 = document.createElement('a');
            a3.className='btn btn-sec btn-small';
            a3.setAttribute('onclick', "PAPI.panel.validateChildAgesPanel('"+i+"','exit',this);PAPI.panel.validateInfantsAndAdults();");
            a3.innerHTML='OK';
            divPanelAges6.appendChild(a3);
            divPanelAges3.appendChild(divPanelAges4);
            divPanelAges1.appendChild(divPanelAges3);
            divPanelAges1.appendChild(divPanelAges6);
            divChildren1.appendChild(divPanelAges1);
            fieldSet.appendChild(divChildren1);
            var divPanelAges7 = document.createElement('div');
            divPanelAges7.className='cell';
            divPanelAges7.id='childAgeWarning'+i;
            divPanelAges7.setAttribute('style','display:none;');
            divPanelAges7.innerHTML='<strong>Child age tip</strong>- One adult is required for each travelling child under the age of 2.';
            fieldSet.appendChild(divPanelAges7);
            var divPanelAges8 = document.createElement('div');
            divPanelAges8.id='maxPaxWarning'+i;
            divPanelAges8.className='alert assist';
            divPanelAges8.setAttribute('style','display:none;');
            divPanelAges8.innerHTML='<strong>Want to book with more than9persons? </strong>- Please call 0844 879 8493 to speak to one of our advisors who will help you with your holiday needs.';
            fieldSet.appendChild(divPanelAges8);
            $('#paxCombination div.multiRooms').before(fieldSet);
        }
        i=i-1;
        if((numberOfPaintedRooms==0||numberOfPaintedRooms==1)&&!displayNoneEnabled){
            for(var e=0;e<=maxNumberOfRooms;e++){
                $('#containerPanel').removeClass('multiRoom_'+e);
            }
            if(numberOfPaintedRooms==0){
                $('#containerPanel').addClass('multiRoom_2');
                $("#addroom").hide();
                $("#removeroom").show();
            }else if(numberOfPaintedRooms==1){
                $('#containerPanel').addClass('multiRoom_1');
                $("#removeroom").show();
                $("#removeroom").removeClass("hideAll");
                $("#addroom").addClass("hideAll");
                $("#addroom").show();
            }
        }
    }

	var removeMaxChildrenAgeMsg = function(){
		$('[name="maxChildAgeMessage"]').each(function( index ) {
			$(this).css("display", "none");
		});
	}

	var displayMaxChildrenAgeMsg = function(){
		$('[name="maxChildAgeMessage"]').each(function( index ) {
			$(this).css("display", "block");
		});
	}
	var checkChildrenNumber = function(){

        var numChildren = 0;
        $('[id^="numChildren"]').each(function(index) {
            numChildren +=parseInt($("option:selected", this).text());
        });
        if (numChildren > 0){
            displayMaxChildrenAgeMsg();
        }else{
            removeMaxChildrenAgeMsg();
        }
    }

	var getTopDestination=function(){
    	$(".topDestinations-bd li ").bind("click", function() {
    	var key = $(this).text();
    	var destination = mapTopDestinations[key];
        $.ajax({url:urlPath,  crossDomain : true, dataType:'json', data:{resort: destination},
        	headers: {'SESSIONID':getCookie("JSESSIONID"), 'DEVICEID':getCookie("DEVICEID")},
            success: function(data) {
                $('#srchWhereFrom').val('');
                $('#papiDestination').val('');
                $('#srchWhereFromHidden').val('');
                destinationTags = new Array();
                if(data._embedded.resorts == null || data._embedded.resorts.length == 0){
                    displayDestinationError();
                    $('#destinationDisplay').autocomplete('close');
                    destinationMap = new Array();
                    airportTags = new Array();
                    $("#srchWhereFrom").autocomplete({source: airportTags, appendTo: ".facetsTop", minLength:0});
                }else{
                    hideDestinationError();
                    airportTags = new Array();
                    $.each(data._embedded.resorts, function(index, element) {
                    	if(data._embedded.resorts[index].title == destination) {
                    		$('#destinationDisplay').val(data._embedded.resorts[index].title);
                    		$('#papiDestination').val(data._embedded.resorts[index].code);
                    		$.each(data._embedded.resorts[index]._links.routedSearch.params.depAirport.params.list, function(index, element) {
                                airportMap[index]= new Array(2);
                                airportTags[index] = element.title;
                                airportMap[index][0] = element.title;
                                airportMap[index][1] = element.value;
                            });
                    		 $("#srchWhereFrom").autocomplete({source: airportTags, appendTo: ".facetsTop", minLength:0}).focus(function(){
                                 $("#srchWhereFrom").autocomplete("search");
                             });
                             airporAutompleteActive = true;
                    	}
                    });

                    if (data._embedded.resorts != ''){
                        urlPathPapi = data._embedded.resorts[0]._links.routedSearch.href;
                    }

                }
            }
        });
        $('.topDestinations-bd li').off('click');
        $('.topDestinations-ArrowUp').css('visibility', 'visible');
        $('#topDestinations').removeClass('open');
    	})
    }
    var putZeroInChilds = function(maxNumberOfRooms,roomNumber){
        for(var i=0;i<=maxNumberOfRooms;i++){
            if($('#numAdultsError'+i).is(":visible")){
                for(var e=0;e<=maxNumberOfRooms;e++){
                    $('#numChildren'+e).val(0);
                    $('#editChilds'+e).removeClass('in');
                    $('#editChilds'+e).addClass('fade');
                }
                break;
            }
        }
    }

    return {newSearch : newSearch,
        createMapValue:createMapValue,
        createMapValueList:createMapValueList,
        updatePapiUrl:updatePapiUrl,
        updateContext:updateContext,
        getOccupation:getOccupation,
        updateStars:updateStars,
        initStars:initStars,
        filterUpdate:filterUpdate,
        getBoardType:getBoardType,
        getStars:getStars,
        removePaxError:removePaxError,
        validateForm:validateForm,
        cleanError:cleanError,
        validateInput:validateInput,
        sendForm:sendForm,
        createDatePicker:createDatePicker,
        updateHiddenDate:updateHiddenDate,
        validateMoreThan9Pax:validateMoreThan9Pax,
        //resetChildren:resetChildren,
        validateChildAgesPanel:validateChildAgesPanel,
        validateChildren:validateChildren,
        cleanChildrenError:cleanChildrenError,
        calculatePapiPagination:calculatePapiPagination,
        hideFilters:hideFilters,
        airportAutomcomplete:airportAutomcomplete,
        displayDestinationError:displayDestinationError,
        hideDestinationError:hideDestinationError,
        displayAirportError:displayAirportError,
        hideAirportError:hideAirportError,
        getCookie:getCookie,
        addNewRooms:addNewRooms,
        removeRooms:removeRooms,
        validateInfantsAndAdults:validateInfantsAndAdults,
        positionChilds:positionChilds,
        removeInfantsError:removeInfantsError,
        removeChildsPanel:removeChildsPanel,
        //closeChildAgesPanel:closeChildAgesPanel,
        putZeroInChilds:putZeroInChilds,
        openChildPanelFromButton:openChildPanelFromButton,
		removeMaxChildrenAgeMsg:removeMaxChildrenAgeMsg,
		displayMaxChildrenAgeMsg:displayMaxChildrenAgeMsg,
		checkChildrenNumber:checkChildrenNumber,
		topDestinations:topDestinations,
        renderRoomsAndPax:renderRoomsAndPax,
		getTopDestination:getTopDestination
    }
}(PAPI,jQuery));